/**
 * @author LANG
 * Copyright 2009, QSC.
 * All rights reserved.
 */
float4x4 worldViewProjection : WorldViewProjection;
float4x4 world : WORLD;
float4x4 viewInverse : VIEWINVERSE;
float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
float4x4 lightViewProjection;

float attFactor = 0.1;

struct VertexShaderInput {
	float4 position : POSITION;
	float2 tex :TEXCOORD0;
	float4 normal : NORMAL;
};
  
struct PixelShaderInput {
	float4 position : POSITION;
	float2 tex : TEXCOORD0;  // Texture coordinates
	float4 posLightProj : TEXCOORD2;
	float3 normal : TEXCOORD1;
	float3 worldPosition : TEXCOORD4;
}; 

float4 caluateLight(float3 light_pos, float4 color, PixelShaderInput input)
{
	float3 normal = normalize(input.normal);
  	float3 lightVector = normalize(light_pos - input.worldPosition.xyz);
  
  	float NDotL = dot(normal, lightVector);
  	
	float d = distance(viewInverse[3].xyz, input.worldPosition.xyz);
	d *= 0.1;
	float attenuation = 1/(1+d+d*d);
	
  	return (color*ambient + color*diffuse*NDotL) * attenuation;
}
	
PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
	PixelShaderInput output;

	output.position = mul(input.position, worldViewProjection);
	output.worldPosition = mul(input.position, world).xyz;
	output.normal = mul(input.normal, worldInverseTranspose).xyz;
	
    float4x4 worldLightViewProjection = mul(world, lightViewProjection);
    output.posLightProj = mul(input.position, worldLightViewProjection);
   	output.posLightProj.xyz /= output.posLightProj.w;
   	output.posLightProj.x = 0.5*output.posLightProj.x + 0.5;
   	output.posLightProj.y = -0.5 * output.posLightProj.y + 0.5;
		
	output.tex = input.tex;
	return output;
}
  
float4 pixelShaderFunction(PixelShaderInput input): COLOR {
	float4 color = float4(basicColor, 1);
	if(hasTex){
    	float4 texColor = tex2D(diffuseSampler, input.tex);
    	color = color * texColor;
	}
	if(hasShadowMap){
		float shadow = tex2D(shadow_map, input.posLightProj.xy).r + 0.004  <=  input.posLightProj.z;
		color = (1 - shadow * 0.8)  * color ;
	}
	color = caluateLight(lightWorldPos, color, input);
	//modify the opacity
	color.w = opacity;
	if(isHighlight){
		return color * 0.5 + highlightColor * 0.5;
	}
	return color;
}
  
// #o3d VertexShaderEntryPoint vertexShaderFunction
// #o3d PixelShaderEntryPoint pixelShaderFunction
// #o3d MatrixLoadOrder RowMajor